package com.demo.crawler;

/**
 * Created by lenovo on 2017/6/20.
 */

import com.google.common.collect.Lists;

import com.demo.entity.Sale;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

/**
 * @author lepdou 2017-06-18
 */
@Component
public class SaleDataParser {
    private static final Map<String, String> classNameMapNum = new HashMap();
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @PostConstruct
    public void init() {
        classNameMapNum.put("numbzero", "0");
        classNameMapNum.put("numbone", "1");
        classNameMapNum.put("numbtwo", "2");
        classNameMapNum.put("numbthree", "3");
        classNameMapNum.put("numbfour", "4");
        classNameMapNum.put("numbfive", "5");
        classNameMapNum.put("numbsix", "6");
        classNameMapNum.put("numbseven", "7");
        classNameMapNum.put("numbeight", "8");
        classNameMapNum.put("numbnine", "9");
        classNameMapNum.put("numbdor", ".");
    }

    public List<Sale> parse(String html) {
        Document document = Jsoup.parse(html);

        Element dataContent = document.getElementsByClass("tm-datanowlist").get(0);
        Elements salesDataDom = dataContent.getElementsByTag("li");

        List<Sale> sales = Lists.newArrayList();
        for (Element e : salesDataDom) {
            sales.add(parse(e));
        }

        return sales;
    }

    private Sale parse(Element element) {
        Elements tds = element.getElementsByTag("td");

        Sale sale = new Sale();

        sale.setHouse(parseHouseName(tds.get(0)));
        sale.setPrice(parseAvgPrice(tds.get(3)));

        sale.setCreateDate(dateFormat.format(new Date()));

        return sale;
    }

    private String parseHouseName(Element e) {
        return e.getElementsByTag("a").get(0).text();
    }

    private int parseAvgPrice(Element e) {
        Elements numbers = e.getElementsByTag("span");

        StringBuilder avgPrice = new StringBuilder();
        for (Element num : numbers) {
            Set<String> numCodes = num.classNames();
            for (String numCode : numCodes) {
                avgPrice.append(classNameMapNum.get(numCode));
            }
        }

        return Integer.parseInt(avgPrice.toString());
    }
}
